<?php
/**
 * 小程序
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Weixin;
use app\common\model\UserForm;
use think\Db;
use think\Exception;

class Smallapp extends Api {
	protected $noNeedRight = ['*'];
	
	protected $noNeedLogin = ['login'];
	
	
	/**
	 * 注册及登录
	 */
	public function login() {
		$code = $this->request->post('code');
		!$code && $this->error('参数错误');
		
		$weinxin = new Weixin();
		$res = $weinxin->getOpenId($code);
		if(!isset($res['openid'])) {
			$this->error('登录出错');
		}
		
		$openid = $res['openid'];
		$user = \app\common\model\User::get(['openid' => $openid]);
		if(!$user) {
			$username = 'wx_' . mt_rand(111111, 999999);
			$password = mt_rand(111111, 999999);
			$res = $this->auth->register($username, $password, '', '', ['openid' => $openid]);
			if (!$res) {
				$this->error($this->auth->getError());
			}
			
			$userId = $this->auth->id;
		} else {
			$userId = $user['id'];
		}
		
		$this->auth->direct($userId);
		$userInfo = $this->auth->getUserinfo();
		$this->success($user?'登录成功':'注册成功', $userInfo);
	}
	
	/**
	 * 绑定老帐号
	 */
	public function bindAccount() {
		$account = $this->request->post('account');
		$password = $this->request->post('password');
		$userId = $this->auth->id;
		$openid = $this->auth->openid;
		
		if($this->auth->mobile) {
			$this->error('该帐号已绑定了手机号');
		}
		
		if (!$account || !$password) {
			$this->error(__('Invalid parameters'));
		}
		$ret = $this->auth->login($account, $password);
		if ($ret) {
			Db::startTrans();
			try {
				//有帐号
				$delRes = Db::name('user')
					->where(['id' => $userId])
					->update(['openid' => '']);
				if(!$delRes) {
					throw new Exception('删除新帐号openid出错');
				}
				
				$res = Db::name('user')
					->where(['id' => $this->auth->id])
					->update(['openid' => $openid]);
				if(!$res) {
					throw new Exception('更改原帐号openid出错');
				}
				
				Db::commit();
				$this->success('绑定原帐号成功', $this->auth->getUserinfo());
			} catch (Exception $e) {
				Db::rollback();
				$this->error('绑定原帐号出错');
			}
		} else {
			$this->error('帐号密码不正确');
		}
	}
	
	
	/**
	 * 保存用户表单
	 */
	public function saveFormId() {
		$formId = $this->request->post('form_id');
		!$formId && $this->error('参数错误');
		
		if($formId == 'the formId is a mock one') {
			$this->success('测试数据');
		}
		
		$model = new UserForm();
		$res = $model->isUpdate(false)
			->save([
				'user_id' => $this->auth->id,
				'form_id' => $formId
			]);
		
		if($res) {
			$this->success('记录成功');
		} else {
			$this->error('记录出错');
		}
	}
}
